package model.datareader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import model.exception.FileReadException;

/**
 * 
 * @author Jei Min Yoo
 * @author Michael Deng (edited)
 *
 */
public class CSVReader extends AbstractReader {

    private String myFilePath;
    private List<List<String>> myData;

    /**
     * CSV reader constructor
     */
    public CSVReader () {
        super();
    }

    @Override
    public void readFile (String filePath) {
        myData = super.getData();
        myFilePath = filePath;
        super.readFile(filePath);
    }

    @Override
    protected void extractData () {
        try {
            File file = new File(myFilePath);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            parseLines(reader);
            reader.close();
        }
        catch (FileNotFoundException e) {
            throw new FileReadException("File is not found.");
        }
        catch (IOException e) {
            throw new FileReadException("IO Exception.");
        }
    }

    private void parseLines (BufferedReader reader) throws IOException {
        String line;
        int row = 0;

        while ((line = reader.readLine()) != null) {
            myData.add(new ArrayList<String>());
            String[] parsedStringArray = line.split(",");
            for (String parsedString : parsedStringArray) {
                myData.get(row).add(parsedString);
            }
            row++;
        }
    }
}
